<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="内容">
          <el-input v-model="queryParams.content" placeholder="请输入评论内容关键词" clearable />
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="待审核" :value="0" />
            <el-option label="已屏蔽" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-container">
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="warning" :disabled="selectedIds.length === 0" @click="handleBatchBlock">批量屏蔽</el-button>
      <el-button type="success" :disabled="selectedIds.length === 0" @click="handleBatchApprove">批量通过</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="commentList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="评论内容" prop="content" min-width="250" show-overflow-tooltip />
      <el-table-column label="发布用户" width="120" align="center">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="30" :src="row.avatar || defaultAvatar" />
            <span class="username">{{ row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属帖子" prop="postTitle" min-width="180" show-overflow-tooltip>
        <template #default="{ row }">
          <el-link type="primary" @click="viewPost(row.postId)">{{ row.postTitle }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="点赞数" prop="likeCount" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.status === 1" type="success">正常</el-tag>
          <el-tag v-else-if="row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else type="danger">已屏蔽</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" prop="createTime" width="160" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button v-if="row.status === 0" type="text" @click="handleApprove(row)">通过</el-button>
          <el-button v-if="row.status !== 2" type="text" style="color: #E6A23C" @click="handleBlock(row)">屏蔽</el-button>
          <el-button v-if="row.status === 2" type="text" style="color: #67C23A" @click="handleRestore(row)">恢复</el-button>
          <el-button type="text" @click="handleReply(row)">回复</el-button>
          <el-button type="text" style="color: #F56C6C" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 回复评论对话框 -->
    <el-dialog
      v-model="dialog.visible"
      title="回复评论"
      width="600px"
      destroy-on-close
    >
      <div class="reply-dialog">
        <div class="original-comment">
          <div class="comment-user">
            <el-avatar :size="30" :src="commentDetail.avatar || defaultAvatar" />
            <span class="username">{{ commentDetail.username }}</span>
          </div>
          <div class="comment-content">{{ commentDetail.content }}</div>
          <div class="comment-time">{{ commentDetail.createTime }}</div>
        </div>
        <el-form
          ref="replyFormRef"
          :model="replyForm"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="回复内容" prop="content">
            <el-input
              v-model="replyForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
          <el-form-item label="身份显示">
            <el-radio-group v-model="replyForm.isAdmin">
              <el-radio :label="true">管理员身份</el-radio>
              <el-radio :label="false">普通用户身份</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 帖子预览对话框 -->
    <el-dialog
      v-model="postDialog.visible"
      title="帖子详情"
      width="800px"
      append-to-body
    >
      <div class="post-preview" v-loading="postDialog.loading">
        <h2 class="post-title">{{ postDetail.title }}</h2>
        <div class="post-info">
          <span>作者：{{ postDetail.username }}</span>
          <span>发布时间：{{ postDetail.createTime }}</span>
          <span>阅读量：{{ postDetail.viewCount }}</span>
        </div>
        <div class="post-content" v-html="postDetail.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommentList, getCommentDetail, replyComment, updateCommentStatus, deleteComment } from '@/api/forum'
import { getPostDetail } from '@/api/forum'

const loading = ref(false)
const commentList = ref([])
const total = ref(0)
const selectedIds = ref([])
const replyFormRef = ref()
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  content: '',
  username: '',
  status: ''
})

// 表单校验规则
const rules = {
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

// 对话框状态
const dialog = reactive({
  visible: false
})

// 帖子预览对话框状态
const postDialog = reactive({
  visible: false,
  loading: false
})

// 评论详情对象
const commentDetail = reactive({
  id: '',
  content: '',
  username: '',
  avatar: '',
  createTime: '',
  postId: '',
  postTitle: ''
})

// 帖子详情对象
const postDetail = reactive({
  id: '',
  title: '',
  content: '',
  username: '',
  createTime: '',
  viewCount: 0
})

// 回复表单对象
const replyForm = reactive({
  commentId: '',
  content: '',
  isAdmin: true
})

// 获取评论列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCommentList(queryParams)
    commentList.value = res.data.rows
    total.value = res.data.total
  } catch (error) {
    console.error('获取评论列表失败', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.content = ''
  queryParams.username = ''
  queryParams.status = ''
  handleQuery()
}

// 表格选择行变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 查看帖子
const viewPost = async (postId) => {
  postDialog.loading = true
  postDialog.visible = true
  try {
    const res = await getPostDetail(postId)
    Object.assign(postDetail, res.data)
  } catch (error) {
    console.error('获取帖子详情失败', error)
  } finally {
    postDialog.loading = false
  }
}

// 回复评论
const handleReply = async (row) => {
  try {
    const res = await getCommentDetail(row.id)
    Object.assign(commentDetail, res.data)
    replyForm.commentId = row.id
    replyForm.content = ''
    replyForm.isAdmin = true
    dialog.visible = true
  } catch (error) {
    console.error('获取评论详情失败', error)
  }
}

// 提交回复
const submitReply = async () => {
  replyFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      await replyComment(replyForm)
      ElMessage.success('回复成功')
      dialog.visible = false
      getList()
    } catch (error) {
      console.error('回复失败', error)
    }
  })
}

// 通过评论
const handleApprove = (row) => {
  ElMessageBox.confirm('确认通过此评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateCommentStatus(row.id, 1)
    ElMessage.success('操作成功')
    getList()
  }).catch(() => {})
}

// 屏蔽评论
const handleBlock = (row) => {
  ElMessageBox.confirm('确认屏蔽此评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateCommentStatus(row.id, 2)
    ElMessage.success('屏蔽成功')
    getList()
  }).catch(() => {})
}

// 恢复评论
const handleRestore = (row) => {
  ElMessageBox.confirm('确认恢复此评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateCommentStatus(row.id, 1)
    ElMessage.success('恢复成功')
    getList()
  }).catch(() => {})
}

// 删除评论
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除此评论吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteComment(row.id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 批量通过评论
const handleBatchApprove = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要操作的数据')
    return
  }
  
  ElMessageBox.confirm(`确认通过选中的 ${selectedIds.value.length} 条评论吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateCommentStatus(selectedIds.value.join(','), 1)
    ElMessage.success('批量通过成功')
    getList()
  }).catch(() => {})
}

// 批量屏蔽评论
const handleBatchBlock = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要操作的数据')
    return
  }
  
  ElMessageBox.confirm(`确认屏蔽选中的 ${selectedIds.value.length} 条评论吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateCommentStatus(selectedIds.value.join(','), 2)
    ElMessage.success('批量屏蔽成功')
    getList()
  }).catch(() => {})
}

// 批量删除评论
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条评论吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteComment(selectedIds.value.join(','))
    ElMessage.success('批量删除成功')
    getList()
  }).catch(() => {})
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .action-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    
    .username {
      margin-left: 8px;
    }
  }
  
  .reply-dialog {
    .original-comment {
      padding: 15px;
      border-radius: 4px;
      background-color: #f8f9fa;
      margin-bottom: 20px;
      
      .comment-user {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        
        .username {
          margin-left: 8px;
          font-weight: bold;
        }
      }
      
      .comment-content {
        padding: 5px 0;
        line-height: 1.6;
      }
      
      .comment-time {
        font-size: 12px;
        color: #999;
        text-align: right;
        margin-top: 8px;
      }
    }
  }
  
  .post-preview {
    padding: 10px;
    
    .post-title {
      font-size: 20px;
      margin-bottom: 15px;
      text-align: center;
    }
    
    .post-info {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
      font-size: 14px;
      color: #666;
      
      span {
        margin: 0 10px;
      }
    }
    
    .post-content {
      line-height: 1.8;
    }
  }
}
</style> 